package service

import (
	"github.com/wonderivan/logger"
	"payment/app/validator"
	"payment/channel"
	"payment/dao"
	"payment/model"
)

var payEntryService *PayEntryService

type PayEntryService struct {
}

func GetPayEntryService() *PayEntryService {
	if payEntryService == nil {
		payEntryService = new(PayEntryService)
	}
	return payEntryService
}

/**
出金
*/
func (ps *PayEntryService) CreateInOrder(payEntryArg validator.PayEntryValidator) (*model.PayEntry, string) {
	//根据支付渠道创建付款对象
	payInstance := channel.GetPayInstance(payEntryArg.PayChannel)
	if payInstance == nil {
		return nil, "CHANNEL_ERROR"
	}
	pEntry := new(model.PayEntry)
	pEntry, err := payInstance.CreateOrder(payEntryArg)
	if pEntry == nil || err != nil {
		return nil, "INTERNAL_ERROR"
	}
	return pEntry, ""
}

/**
 * 获得付款订单状态
 * param: string           orderId
 * param: model.PayChannel payChannel
 * return: interface{}
 * return: string
 */
func (ps *PayEntryService) GetPayOrderStatus(paymentId string, orderId string) (status model.PayStatus, resKey string) {
	engine, err := dao.GetMysql()
	if err != nil {
		logger.Error("PayEntryService_GetPayOrderStatus_DBError | err=%v | paymentId=%+v", err, paymentId)
		return "", "DB_ERROR"
	}
	payEntry := new(model.PayEntry)
	exist, err := engine.Where("payment_order_id=?", orderId).Get(payEntry)
	if err != nil {
		logger.Error("PayEntryService_GetPayOrderStatus_QueryError | err=%v | orderId=%+v", err, paymentId)
		return "", "DB_ERROR"
	}
	if !exist {
		return "", "NOT_EXIST"
	}
	//根据支付渠道创建付款对象
	payInstance := channel.GetPayInstance(payEntry.PayChannel)
	if payInstance == nil {
		return "", "CHANNEL_ERROR"
	}
	status, err = payInstance.Inquiry(paymentId, orderId)
	if err != nil {
		logger.Error("PayEntryService_GetPayOrderStatus_Error | err=%v | orderId=%+v", err, paymentId)
		return "", "REQUEST_ERROR"
	}
	return status, ""
}

func (ps *PayEntryService) WebHookCallback(hook *model.CallBackWebHook) (resKey string) {
	engine, err := dao.GetMysql()
	if err != nil {
		logger.Error("PayEntryService_WebHookCallback_DBError | err=%v", err)
		return "DB_ERROR"
	}
	switch hook.Event {
	//订单付款成功
	case model.OrderPaid:
		payEntry := new(model.PayEntry)
		payEntry.PaymentId = hook.PayLoad.Payment.Entity.Id
		payEntry.Status = model.PAYSUCCESS
		_, err := engine.Where("payment_order_id=?", hook.PayLoad.Order.Entity.Id).Update(payEntry)
		if err != nil {
			logger.Error("PayEntryService_WebHookCallback_Err | err=%v", err)
			return "DB_ERROR"
		}
		//发起回调
		//ps.SendEntryCallback(payEntry)
	//订单付款失败
	case model.PaymentFailed:
		payEntry := new(model.PayEntry)
		payEntry.PaymentId = hook.PayLoad.Payment.Entity.Id
		payEntry.Status = model.PAYFAILD
		_, err := engine.Where("payment_order_id=?", hook.PayLoad.Order.Entity.Id).Update(payEntry)
		if err != nil {
			logger.Error("PayEntryService_WebHookCallback_Err | err=%v", err)
			return "DB_ERROR"
		}
	}
	return ""
}

/**
 *
 */
func (ps *PayEntryService) SendEntryCallback(payEntry *model.PayEntry) {

}
